<template>
  <view class="body">
    <goods-swipe :banners="info.pictures"></goods-swipe>
    <view class="goods-info good-item">
      <view class="flex items-center mb-base">
        <view class="goods-name flex-1">
          {{ info.name }}
        </view>
        <view class="goods-divider"></view>
        <view class="goods-share" @click.stop="shareClick">
          <image :src="ossImg('others/goods/share.png')" />
          <view>分享</view>
        </view>
      </view>
      <view class="flex items-center justify-between leading-none goods-price">
        <view class="flex items-end price">
          {{ info.lowestPrice }}
          <label v-if="info.originalPrice !== 0"
            >¥{{ info.originalPrice }}</label
          >
        </view>
        <label style="color: #818181">已销{{ info.sales }}件</label>
      </view>
    </view>
    <!-- coupon list -->
    <view class="my-2 good-item">
      <oreo-cell label="优惠" scroll @click="openVisible" @arrow="openVisible">
        <view class="coupon-list">
          <view class="coupon-tag primary">领劵</view>

          <view class="coupon-tag" v-for="item in couponList" :key="item.id"
            >{{
              item.threshold !== 0
                ? `满${item.threshold}减${item.maxOff}`
                : `无门槛减${item.maxOff}`
            }}
          </view>
        </view>
      </oreo-cell>
      <oreo-cell
        label="规格"
        @click.stop="openSkuPanel('confirm')"
        v-if="info.productSkus.length !== 1"
      >
        <view :style="{ color: sku === '' ? '#979797' : '' }">{{
          sku || "请选择规格"
        }}</view>
      </oreo-cell>
    </view>
    <view class="mb-2 good-item">
      <!-- <oreo-cell label="送至">
        <view>上海市上海市徐汇区龙华西路285弄17....</view>
      </oreo-cell> -->
      <oreo-cell label="服务" :arrow="false">
        <view>仅支持快递发货</view>
      </oreo-cell>
    </view>
    <view class="goods-notice good-item">
      <image :src="ossImg('others/goods/laba@2x.png')" />
      <view class="notice-content"
        >运力已恢复，非中高风险地区，下单后48小时内发货。</view
      >
    </view>
    <!-- goods content -->
    <view class="goods-detail good-item">
      <view class="goods-title">商品详情</view>
      <view class="goods-content" v-html="info.intro">
        <!--   content   -->
      </view>
    </view>

    <!-- 购物车更多商品 -->
    <view class="moreGoods good-item">
      <recommend-goods :listData="goodsList"
    /></view>

    <!-- Header back -->
    <view class="header-back" :style="{ height: `${headHeight * 2}rpx` }">
      <image
        :style="{ top: `${(backPostion + 9) * 2}rpx` }"
        :src="ossImg('others/goods/back@2x.png')"
        @click="backMall()"
      />
    </view>
    <!-- footer action -->
    <oreo-goods-action>
      <oreo-goods-action-icon text="首页" @click.stop="backHome">
        <template v-slot:icon>
          <image
            class="action-icon"
            :src="ossImg('others/goods/index_icon@2x.png')"
          />
        </template>
      </oreo-goods-action-icon>
      <button open-type="contact" class="kfbtn">
        <oreo-goods-action-icon text="客服" @click.stop="toKefu">
          <template v-slot:icon>
            <image
              class="action-icon"
              :src="ossImg('others/goods/kf_icon@2x.png')"
            />
          </template>
        </oreo-goods-action-icon>
      </button>

      <uni-badge
        class="uni-badge-left-margin"
        :text="cartCount"
        absolute="rightTop"
        size="small"
        :customStyle="{
          color: '#ffffff',
          right: '6px',
          top: '-9px',
          background: '#0058C6',
        }"
      >
        <oreo-goods-action-icon text="购物车" @click.stop="backCart">
          <template v-slot:icon>
            <image
              class="action-icon"
              :src="ossImg('others/goods/buy_icon@2x.png')"
            />
          </template>
        </oreo-goods-action-icon>
      </uni-badge>

      <oreo-goods-action-button
        text="加入购物车"
        color="#D4DDFE"
        @click.stop="openSkuPanel('cart')"
      />
      <oreo-goods-action-button
        text="立即购买"
        color="#0058C6"
        @click.stop="openSkuPanel('confirm')"
      />
    </oreo-goods-action>

    <!-- 优惠券选择列表 -->
    <oreo-popup :show="visible" round position="bottom">
      <goods-coupon-list
        @close="onCloseCoupon"
        @getGoodsCoupon="getGoodsCoupon"
        :couponList="couponList"
      />
    </oreo-popup>
    <!-- 商品分享 -->
    <oreo-popup :show="shareVisible" round position="bottom">
      <goods-share @poster="handleCreatePoster" @close="shareVisible = false" />
    </oreo-popup>
    <!-- SKU选择 -->
    <oreo-popup round :show="skuVisible" position="bottom">
      <product-sku
        v-if="skuVisible"
        :product="info"
        :chooseType="chooseType"
        @confirm="handleChooseSku"
        @close="skuVisible = false"
        @skuChange="handleSku"
      />
    </oreo-popup>
    <!--  海报绘制  -->
    <poster ref="posterRef" :info="info" />
  </view>


</template>

<script setup>
import GoodsSwipe from "@/components/goods-swipe";
import OreoCell from "@/components/oreo-cell";
import GoodsCouponList from "@/components/goods-coupon-list";
import GoodsShare from "@/components/goods-share";
import RecommendGoods from "@/components/recommend-goods.vue";
import { reactive, ref } from "vue";
import { GetGoodsDetail, AddProduct2Cart } from "@/services/mall";
import { GetgoodsCouponList } from "@/services/coupon";
import { GetCartGoods } from "@/services/cart";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import ProductSku from "@/components/product-sku";
import { message, ossImg } from "@/utils/utils";
import Poster from "@/components/poster";
import UniBadge from "@/components/uni-badge/uni-badge.vue";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const visible = ref(false);
const posterRef = ref(null);
const shareVisible = ref(false);
const skuVisible = ref(false);
const chooseType = ref("");
const couponList = ref([]);
const headHeight = ref(0);
const backPostion = ref(0);
const sku = ref("");
const goodsList = ref([]);
const cartCount = ref(getApp().globalData.cartCount);

const info = reactive({
  intro: [],
  pictures: [],
  productSkus: [],
});

onLoad((option) => {
  getDetail(option.id);

  //#ifdef MP-WEIXIN
  wx.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
  //#endif
});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();

  // 获取状态栏高度
  const { statusBarHeight } = uni.getSystemInfoSync();
  // 获取胶囊位置尺寸
  const menuButtonObject = uni.getMenuButtonBoundingClientRect();
  const { top, height } = menuButtonObject;
  // 获取导航栏的高度
  const navBarHeight = height + (top - statusBarHeight) * 2;
  // 计算状态栏与导航栏的总高度
  const statusNavBarHeight = statusBarHeight + navBarHeight;
  headHeight.value = statusNavBarHeight;
  backPostion.value = menuButtonObject.top;
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    `product_detail_page_${info.id}`,
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    `product_detail_page_${info.id}`,
    stayTime
  );
});

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1].route;
  const pageUrl = currentPage + "?id=" + info.id;

  const shareObj = {
    title: info.shareDescription !== "" ? info.shareDescription : info.name, // 默认是小程序的名称(可以写slogan等)
    path: pageUrl, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: info.shareImageUrl !== null ? info.shareImageUrl : info.imageUrl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});

const getCartGoods = async () => {
  const res = await GetCartGoods();
  if (res?.code === 200) {
    goodsList.value = res.data.list;
  } else {
    message(res.message);
  }
};

const openSkuPanel = (key) => {
  // 判断是否登录
  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    uni.setStorageSync("REDIRECT_URI", JSON.stringify());
    uni.navigateTo({ url: "/pages/vip/register" });
    return;
  }
  if (
    getApp().globalData.user.nickname === null ||
    getApp().globalData.user.nickname === "" ||
    getApp().globalData.user.nickname === undefined
  ) {
    console.log(1);
    // cachePath.value = { path, redirect };
    return getApp().getWechatUserProfile({ navigateBack: true });
  }

  if (info?.saleable === 0) return message("商品已下架~");
  chooseType.value = key;
  if (chooseType.value === "confirm") {
    skuVisible.value = true;
  } else if (chooseType.value === "cart") {
    getApp().emdlz2("track", "event", "store_page", "click", "cart", "");
    skuVisible.value = true;
  }
};

const handleChooseSku = async ({ productSkuId, quantity }) => {
  if (chooseType.value === "confirm") {
    getApp().emdlz2(
      "track",
      "event",
      "store_page",
      "click",
      `purchase_now_${info.id}`,
      ""
    );
    uni.navigateTo({
      url: `/pages/goods/order?productSkuId=${productSkuId}&quantity=${quantity}`,
    });
  } else if (chooseType.value === "cart") {
    addCart({ productSkuId, quantity });
  }
};

const addCart = async ({ productSkuId, quantity }) => {
  const res = await AddProduct2Cart({ productSkuId, quantity });
  if (res?.code === 200) {
    skuVisible.value = false;

    getApp()
      .sr()
      .track("add_to_cart", {
        action_type: "append_to_cart",
        sku: {
          sku_id: productSkuId,
          sku_name: sku.value,
        },
        spu: {
          spu_id: productSkuId, // 若商品无spu_id时，可传sku_id信息
          spu_name: sku.value, // 若商品无spu_name时，可传sku_name信息
        },
        sku_num: quantity,
        // more...
      });

    getApp().emdlz2(
      "track",
      "event",
      "store_page",
      "click",
      `add_to_cart_${info.id}`,
      ""
    );
    getApp()
      .getCartCount()
      .then((res) => {
        cartCount.value = res;
      });

    message("加入购物车成功～");
  } else {
    message("加入购物车失败：" + res.message);
  }
};

const handleSku = (skuItem) => {
  sku.value = skuItem.key + "*" + skuItem.value;
};

const backHome = () => {
  getApp().emdlz2("track", "event", "homepage", "click", "homepage", "");
  uni.switchTab({
    url: "/pages/home/home",
  });
};

const backCart = () => {
  getApp().emdlz2("track", "event", "homepage", "click", "cart", "");
  uni.switchTab({
    url: "/pages/cart/cart",
  });
};

const toKefu = () => {
  getApp().emdlz2("track", "event", "homepage", "click", "customer_service", "");
  getApp().sr().track("start_consult", {
    action_type: "consult_online",
    // more...
  });
};

const onCloseCoupon = () => {
  visible.value = false;
};
const openVisible = () => {
  visible.value = true;
  for (const item of couponList.value) {
    getApp()
      .sr()
      .track("expose_coupon", {
        coupon: [
          {
            coupon_id: item.id,
            coupon_name: item.name,
          },
        ],
        coupon_package: {
          coupon_package_id: item.id,
          coupon_package_name: item.name,
        },
        coupon_batch: {
          coupon_batch_id: item.id,
          coupon_batch_name: item.name,
        },
        // more...
      });
  }
};

const backMall = () => {
  console.log(getCurrentPages()[getCurrentPages().length - 2]);
  if (
    getCurrentPages()[getCurrentPages().length - 2] === undefined ||
    getCurrentPages()[getCurrentPages().length - 2].$page.fullPath ===
      "/pages/loading/loading"
  ) {
    uni.switchTab({
      url: "/pages/home/home",
    });
  } else {
    uni.navigateBack({
      delta: 1,
    });
  }
};

const getDetail = async (id) => {
  console.log(id);
  const res = await GetGoodsDetail(id);
  if (res?.code === 200) {
    res.data.pictures = res.data.pictures.sort(function (a, b) {
      return parseInt(a.name) - parseInt(b.name);
    });

    Object.assign(info, res.data);

    // 有数埋点
    for (const item of res.data.productSkus) {
      console.log(1);
      getApp()
        .sr()
        .track("browse_sku_page", {
          sku: {
            sku_id: item.id, // 若商品无sku_id时，可传spu_id信息
            sku_name: skuLabel(item.spData), // 若商品无sku_name时，可传spu_name信息
          },
          spu: {
            spu_id: item.id, // 若商品无spu_id时，可传sku_id信息
            spu_name: skuLabel(item.spData), // 若商品无spu_name时，可传sku_name信息
          },
        });
    }
  } else {
    message(res.message);
  }
  getCartGoods();
  if (uni.getStorageSync("TOKEN")) {
    getGoodsCoupon(id);
  }
};

const getGoodsCoupon = async () => {
  const body = {
    productId: info.id,
    body: {
      pageSize: 500,
      pageNum: 1,
    },
  };
  const res = await GetgoodsCouponList(body);
  if (res?.code === 200) {
    couponList.value = res.data.list;
  } else {
    message(res.message);
  }
};

const handleCreatePoster = () => {
  shareVisible.value = false;
  console.log(posterRef);
  posterRef.value.createPoster(info, posterRef);
};

const shareClick = () => {
  getApp().emdlz2("track", "event", "store_page", "click", "product_share", "");
  shareVisible.value = true;
};

const skuLabel = (skuData) => {
  return skuData.map(({ value, key }) => `${key}${value}`).join(" ");
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.body {
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 64px;
  position: relative;
}

.good-item {
  width: 100%;
  box-sizing: border-box;
}

.kfbtn {
  padding: 0px;
}

.kfbtn::after {
  border: 0px !important;
}

.goods-detail {
  .goods-title {
    width: 100%;
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    text-align: center;
    background: #f7f7f7;
  }
}

.goods-notice {
  font-size: 12px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  background: white;
  width: 100%;
  height: 32px;

  image {
    width: 17px;
    height: 16px;
    margin-right: 12px;
  }

  .notice-content {
    flex: 1;
    font-size: 12px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.coupon-list {
  display: flex;

  .coupon-tag {
    padding: 0 6px;
    height: 20px;
    line-height: 20px;
    white-space: nowrap;
    background: #ffffff;
    color: @primary-color;
    border: 1px solid @primary-color;
    display: inline-block;
    border-radius: 4px;
    font-size: 12px;
    margin-right: 4px;

    &.primary {
      background: @primary-color;
      color: white;
    }
  }
}

.header-back {
  position: fixed;
  top: 0;
  width: 100%;

  image {
    width: 12px;
    height: 18px;
    position: absolute;
    margin-left: 26px;
  }
}

.goods-info {
  background: white;
  padding: 16px 14px;
  box-sizing: border-box;

  .goods-name {
    font-size: 18px;
    font-weight: 400;
    color: #0d0d0d;
    padding-right: 10px;
    line-height: 24px;
  }

  .goods-divider {
    width: 1px;
    height: 17px;
    background: #ebebeb;
  }

  .goods-share {
    white-space: nowrap;
    color: #818181;
    font-size: 12px;
    padding-left: 16px;
  }

  .goods-price {
    color: @primary-color;
    font-size: 16px;

    .price {
      label {
        text-decoration: line-through;
        opacity: 0.51;
        margin-left: 11px;
      }
    }

    label {
      font-size: 12px;
    }
  }

  image {
    width: 20px;
    height: 20px;
    margin-bottom: 5px;
    display: block;
  }
}

.moreGoods {
  width: 100%;
  box-sizing: border-box;
  background-color: #ffffff;
}

:deep(.van-goods-action) {
  padding-top: 14px;
  height: 36px !important;

  .van-goods-action-button--first {
    .van-button__text {
      color: #0058c6;
    }
  }

  .van-goods-action-button {
    .van-button__text {
      font-size: 16px;
      font-weight: normal;
    }
  }

  button {
    height: 36px !important;
  }

  text {
    color: #0d0d0d;
    font-size: 12px;
  }
}

:deep(.van-button) {
  padding: 0 !important;
}

.action-icon {
  width: 20px;
  height: 20px;
  display: block;
  margin: 0 auto;
  margin-bottom: 3px;
}

.poster {
  :deep(.van-popup) {
    background-color: transparent !important;
  }
}
.uni-badge-left-margin {
  height: 36px;
  margin-left: 0px;
}
</style>
